package oceanwiki.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import oceanwiki.util.RequestContent;
import oceanwiki.util.SnowFlake;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


/**
 * @FileName LogAspect
 * @Description
 * @Author Me
 * @date 2024-09-10
 **/

@Aspect
@Component
public class LogAspect {

    @Autowired
    SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(LogAspect.class);

    /* 定义一个切点*/
    @Pointcut("execution(public * oceanwiki.controller..*Controller.*(..))")
    public void controllerPointcut() {

    }

    //配置前置通知
    @Before("controllerPointcut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        //增加日志流水号
        MDC.put("LOG_ID", String.valueOf(snowFlake.nextId()));

        //开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        String name = signature.getName();

        //打印请求信息
        LOG.info("------------开始------------");
        LOG.info("请求地址：{}", request.getRequestURL().toString());
        LOG.info("类名方法：{}.{}", signature.getDeclaringTypeName(), name);
        LOG.info("远程地址：{}", request.getRemoteAddr());

        //获取用户ip，并存在线程中
        RequestContent.setRemoteAddr(getRemoteIp(request));

        //打印请求参数 参数通过joinPoint
        Object[] args = joinPoint.getArgs();

        Object[] arguments = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest
                    || args[i] instanceof ServletResponse
                    || args[i] instanceof MultipartFile) {
                continue;
            }
            arguments[i] = args[i];


        }
            //排除字段，敏感字段或太长的字段日志不显示
            String[] excludeProperties = {"password", "file"};
            PropertyPreFilters filters = new PropertyPreFilters();
            PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
            excludefilter.addExcludes(excludeProperties);
            LOG.info("请求参数：{}", JSONObject.toJSONString(arguments, excludefilter));

    }

    //环绕通知
    @Around("controllerPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        long startTime = System.currentTimeMillis();
        //执行业务内容返回
        Object result = proceedingJoinPoint.proceed();
        //排除字段，铭感字段或太长的字段日志不显示
        String[] excludeProperties = {"password", "file"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludeProperties);
        LOG.info("返回结果：{}", JSONObject.toJSONString(result, excludefilter));
        LOG.info("-------------结束 耗时：{}ms-------------", System.currentTimeMillis()-startTime);
        return result;
    }

    //获取远程地址方法
    public String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("xforwarded-for");
        if (ip == null || ip.length()== 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-Ip");
        }
        if (ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-proxy-Client-Ip");
        }
        if (ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
